import {
    AlipayCircleOutlined,
    LockOutlined,
    MobileOutlined,
    TaobaoCircleOutlined,
    UserOutlined,
    WeiboCircleOutlined,
} from '@ant-design/icons';
import {
    LoginForm,
    ProFormCaptcha,
    ProFormCheckbox,
    ProFormText,
} from '@ant-design/pro-components';
import { Form, message, Space, Tabs, Button } from 'antd';
import { CSSProperties, useEffect, useRef } from 'react';
import { useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import { ShowError } from '@/utils/message';
import { reg } from '@/utils/validate';
import { history, Link } from 'umi';
import { Ajax } from '@/api/api';
import './index.scss'
type LoginType = 'phone' | 'account';

const iconStyles: CSSProperties = {
    marginInlineStart: '16px',
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '24px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};

export default () => {
    const [form] = Form.useForm()
    const formRef = useRef<ProFormInstance<any>>()
    useEffect(() => {
    }, [])

    const [disabled, setDisabled] = useState<boolean>(false)
    const [loginType, setLoginType] = useState<LoginType>('account');
    const onFinish = (value: any) => {
    }

    const todoSubmit = () => {
        form.validateFields()
            .then(async (value) => {
                if (loginType == 'account') {
                    let res: any = await Ajax.login({
                        account: value.account,
                        password: value.password,
                    })

                    if (res.code == 200) {

                        history.push('/main')
                        sessionStorage.setItem('qftoken', res.token)
                        localStorage.setItem('qfaccount', value.account)
                        localStorage.setItem('qfphone', res.result.phone)
                        localStorage.setItem('qfpass', res.result.password)
                        localStorage.setItem('autoLogin', (value.autoLogin ? '1' : '0'))
                    }
                } else {
                    let res: any = await Ajax.verifyCaptcha(value)
                    if (res.code == 200) {
                        history.push('/main')
                        sessionStorage.setItem('qftoken', res.token)
                        localStorage.setItem('qfaccount', res.result.username)
                        localStorage.setItem('qfphone', res.result.phone)
                    }
                }

            })
            .catch(err => {
                message.error('请输入有效的数据信息')
            })
    }

    const resetData = () => {
        form.resetFields()
    }

    useEffect(() => {

        form.setFieldValue('account', localStorage.getItem('qfaccount'))
        form.setFieldValue('phone', localStorage.getItem('qfphone'))
        setDisabled(reg.phone.test(localStorage.getItem('qfphone')))
        if (localStorage.getItem('autoLogin') == '1') {
            form.setFieldValue('password', localStorage.getItem('qfpass'))
            form.setFieldValue('autoLogin', !!localStorage.getItem('autoLogin'))
        }
    }, [])
    return (
        <div style={{ backgroundColor: 'white', padding: 10, height: 520, width: 420 }}>
            <LoginForm
                form={form}
                formRef={formRef}
                logo="https://tres.gog.cn/gaokao/2021-06-20/60cedefe99e4d.jpg"
                title="柳工教育"
                subTitle="笃志勤学 知行合一"
                actions={
                    <Space>
                        其他登录方式
                        <AlipayCircleOutlined style={iconStyles} />
                        <TaobaoCircleOutlined style={iconStyles} />
                        <WeiboCircleOutlined style={iconStyles} />
                    </Space>
                }
                submitter={{
                    render: (props, doms) => {
                        return [
                            <div style={{ width: '100%', display: 'flex' }}>
                                <Button style={{ flex: 1, margin: '0 5px' }} onClick={todoSubmit} type="primary" key="submit" >
                                    {loginType == 'account' ? '登录' : '验证'}
                                </Button>,
                                {<Button style={{ flex: 1, margin: '0 5px' }} danger key="reset" onClick={resetData}>
                                    重置
                                </Button>}
                            </div>
                        ];
                    },
                }}
            >
                <Tabs
                    centered
                    activeKey={loginType}
                    onChange={(activeKey) => setLoginType(activeKey as LoginType)}
                >
                    <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
                    <Tabs.TabPane key={'phone'} tab={'手机号登录'} />
                </Tabs>
                {loginType === 'account' && (
                    <>
                        <ProFormText
                            name="account"
                            fieldProps={{
                                size: 'large',
                                prefix: <UserOutlined className={'prefixIcon'} />,
                            }}
                            placeholder={'用户名: 请输入用户名'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入用户名!',
                                },
                            ]}
                        />
                        <ProFormText.Password
                            name="password"
                            fieldProps={{
                                size: 'large',
                                prefix: <LockOutlined className={'prefixIcon'} />,
                            }}
                            placeholder={'密码: 请输入密码'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入密码！',
                                },
                                {
                                    pattern: reg.pwd,
                                    message: '请输入6-16位的数字字母密码组合'
                                }
                            ]}
                        />
                    </>
                )}
                {loginType === 'phone' && (
                    <>
                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <MobileOutlined className={'prefixIcon'} />,
                            }}
                            name="phone"
                            placeholder={'手机号'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入手机号！',
                                },
                                { pattern: reg.phone, message: '请输入格式正确的手机号' },
                            ]}
                            onChange={(v: any) => setDisabled(reg.phone.test(v.target.value))}
                        />
                        <ProFormCaptcha

                            countDown={180}
                            fieldProps={{
                                size: 'large',
                                prefix: <LockOutlined className={'prefixIcon'} />,
                            }}
                            captchaProps={{
                                size: 'large',
                                disabled: !disabled,
                                type: 'primary'
                            }}
                            phoneName="phone"
                            placeholder={'验证码'}
                            captchaTextRender={(timing, count) => {
                                if (timing) {
                                    setDisabled(false)
                                    return `${count} ${'S倒计时'}`;
                                }
                                return '获取验证码';
                            }}
                            name="captcha"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入验证码！',
                                },
                                { pattern: reg.code, message: '请输入4位的数字验证码' }
                            ]}
                            onGetCaptcha={async (phone) => {
                                let res: any = await Ajax.sendCaptcha({
                                    phone
                                })
                            }}
                        />
                    </>
                )}
                <div
                    style={{
                        marginBlockEnd: 24,
                    }}

                >
                    {
                        loginType == 'account' && <ProFormCheckbox noStyle name="autoLogin">
                            记住密码
                        </ProFormCheckbox>
                    }
                    <Link

                        to='/findpass'
                        style={{
                            float: 'right',
                            marginBottom: 20
                        }}
                    >
                        忘记密码
                    </Link>
                </div>
            </LoginForm>
        </div>
    );
};